package com.myebills.ebpsfrontend.cust.maxis;

import com.myebills.ebpsfrontend.cust.controller.*;
import com.myebills.ebpsfrontend.cust.utils.*;
import com.checkfree.isolutions.customer.persist.Account;
import com.checkfree.isolutions.customer.persist.User;
import com.checkfree.isolutions.customer.persist.Merchant;
import com.checkfree.isolutions.customer.persist.MerchantHomeImpl;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.*;
import java.util.Date;
import java.text.SimpleDateFormat;

/*import com.myebills.maxis.crm.*;
import com.myebills.maxis.crm.UpdateContactHttpServiceStub.*;
import com.myebills.maxis.crm.UpdateContactClient.*;

import org.apache.axis2.client.*;
import org.apache.axiom.om.*;
import javax.xml.namespace.*;

import org.safehaus.uuid.*;
*/
/**
 * Display an account list for user.
 */
public class CusAddSelfCareServlet_v1r00 extends EbppxTransactionServlet {

    /**
     * Load vector of accounts into request.
     */
    public void doTransaction(
    HttpServletRequest req,
    HttpServletResponse res)
    throws ServletException {
        Connection connection = null;
        Connection connection1 = null;
        Statement stmt = null;
        try {
            final HttpSession session = req.getSession(false);

            if (null == session)
                throw new IllegalStateException("no session established");

            final EbppxUrlManager urlManager = getUrlManager(req);

            // get accounts from session and filter out nulls
            final Vector vecAccountDetails = new Vector();
            final EbppxEcsUser ecsUser = (EbppxEcsUser) session.getAttribute(EbppxConstants.ECS_USER);
            final Vector cfiAccounts = ecsUser.getAccounts();
            final Vector vecBillSubscriptions = new Vector();


            // Load the JDBC driver
            connection = EbppxCusDBUtil.getDbConnection();
            connection1 = EbppxCusDBUtil.getKenanDbConnection();

            stmt = connection.createStatement();

      		connection.setAutoCommit(false);
      		connection1.setAutoCommit(false);


            Date dtUpdateDate = new Date();
            String dateString = DateUtil.formatDate(dtUpdateDate);

            String strCategoryDatabase = EbppxCusDBUtil.getCategoryDatabase(connection1);

            Merchant cfiMerchant = MerchantHomeImpl.singleton().findByName(ecsUser.getMerchantName());
            User cfiUser = getUserHome().findByLogonIdAndMerchant(ecsUser.getUserId(),cfiMerchant);
            cfiUser.setProperty("LastUpdateDate",DateUtil.formatDate(dtUpdateDate,EbppxConstants.DATE_FORMAT));
            req.setAttribute("LastUpdateDate", cfiUser.getProperty("LastUpdateDate"));

            String[] strPhysicalBillSubscription = new String[cfiAccounts.size()];
            final AcctDetails acctDetails = new AcctDetails();
            String cusDatabase = "";

            for(int i=0;i<cfiAccounts.size();i++) {
                final Account cfiAccount = (Account)cfiAccounts.elementAt(i);
                final String strAcctExtKey = cfiAccount.getExternalKey();

	            cusDatabase = EbppxCusDBUtil.getCusDatabase(connection1,strCategoryDatabase,strAcctExtKey);
                final EbppxBillDeliveryDataBean dataBean =  new EbppxBillDeliveryDataBean();

                EbppxAcctDetailsDataBean acctDataBean = new EbppxAcctDetailsDataBean();
                acctDataBean = acctDetails.getAcctDetails(connection,strAcctExtKey);

				// New information
                String strNewSMSNo  = urlManager.getSecureParameter("SMSNo"+i);
                String strNewEMailAdd = urlManager.getSecureParameter("EMailAdd"+i);
                String strNewPhysicalBillSubscription = urlManager.getSecureParameter("PhysicalBillSubscription"+i);
                String strNewAccountSubscription = urlManager.getSecureParameter("AccountSubscription"+i);
                String strNewEmailSubscription = urlManager.getSecureParameter("EmailSubscription"+i);
                String strNewSMSNoSubscription = urlManager.getSecureParameter("SMSNoSubscription"+i);

                // Old information
                String kenanAccounNo = EbppxCusDBUtil.getKenanAccountNo(connection1,strCategoryDatabase,strAcctExtKey);
                String strTemp = EbppxCusDBUtil.processCUSPhysicalBillSubscription(connection1,cusDatabase,strAcctExtKey,strCategoryDatabase);
                if(strTemp!=null){
					if(!strTemp.equals("")){
						if(strTemp.substring(0,1).equals("Y") || strTemp.substring(0,1).equals("N")){
							strPhysicalBillSubscription[i] = strTemp.substring(0,1);
						}else{
							strPhysicalBillSubscription[i] = "N";
						}
					}else{
						strPhysicalBillSubscription[i] = "N";
					}
				}

                String strEMailAdd = "";
                strEMailAdd = acctDataBean.getEmailAdd();
                String strSMSNo = "";
                strSMSNo = acctDataBean.getSMSNo();
                String strAccountSubscription = "0";
                strAccountSubscription = acctDataBean.getAcctSubscription();
                String strEmailSubscription = "0";
                strEmailSubscription = acctDataBean.getEmailSubscription();
                String strSMSNoSubscription = "0";
                strSMSNoSubscription = acctDataBean.getSMSSubscription();

                //Added for bill suppress
				if(EbppxCusDBUtil.checkIfPhysicalBillSubsExist(connection1,cusDatabase,strAcctExtKey,strCategoryDatabase)){//this is used to check if the data exist in the info_cust_text table
					if(strPhysicalBillSubscription[i].equals("N") && strNewPhysicalBillSubscription.equals("Y")){

						// No Physical Bill Subscription
						EbppxCusDBUtil.updateInfoCustText(connection1, cusDatabase,EbppxConstants.NO_PHYSICAL_BILL_SUBSCRIPTION, kenanAccounNo);
              			EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.NO_PHYSICAL_BILL_SUBSCRIPTION, cfiAccount.getExternalKey(), ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strNewSMSNo, "", "", "");
						dataBean.setPhysicalBillSubscription(strNewPhysicalBillSubscription);
					}else if(strPhysicalBillSubscription[i].equals("Y") && strNewPhysicalBillSubscription.equals("N")){

						// No Physical Bill Unsubscription
              			EbppxCusDBUtil.updateInfoCustText(connection1, cusDatabase,EbppxConstants.NO_PHYSICAL_BILL_UNSUBSCRIPTION, kenanAccounNo);
	              		EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.NO_PHYSICAL_BILL_UNSUBSCRIPTION, cfiAccount.getExternalKey(), ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strNewSMSNo, "", "", "");
						dataBean.setPhysicalBillSubscription(strNewPhysicalBillSubscription);
					}else{
						dataBean.setPhysicalBillSubscription(strNewPhysicalBillSubscription);
					}
				}else{//doesn't exist in info_cust_text table
					// New user,insert to info_cust_test
					if(strNewPhysicalBillSubscription.equals("Y")){
						// Subscription
						EbppxCusDBUtil.insertInfoCustText(connection1, cusDatabase,EbppxConstants.NO_PHYSICAL_BILL_SUBSCRIPTION, kenanAccounNo);
              			EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.NO_PHYSICAL_BILL_SUBSCRIPTION, cfiAccount.getExternalKey(), ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strNewSMSNo, "", "", "");
						dataBean.setPhysicalBillSubscription(strNewPhysicalBillSubscription);
					}
				}
                  // end added here

				vecBillSubscriptions.addElement(dataBean);

                if(!strNewSMSNo.equals(strSMSNo)){
                    EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.SMS_NO_CHANGE, cfiAccount.getExternalKey(), ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strNewSMSNo, strSMSNo, "", "");
                    //acctDetails.updateSMSNo(connection, strAcctExtKey, strNewSMSNo);
                    acctDataBean.setSMSNo(strNewSMSNo);
                }
                if(!strNewEMailAdd.equals(strEMailAdd)){
                    EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.EMAIL_CHANGE_DELIVERY, cfiAccount.getExternalKey(), ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strNewEMailAdd, strEMailAdd, "", "");
                    //acctDetails.updateEmailAdd(connection, strAcctExtKey,strNewEMailAdd);
                    acctDataBean.setEmailAdd(strNewEMailAdd);

                    // Added for CRM
					/*UpdateContactClient client = new UpdateContactClient();
					boolean success = client.initiateUpdateContact(strAcctExtKey, strNewEMailAdd);
					if(success){
						System.out.println("Successfully update email address");
					}*/
                }


          		// If there is a changes in the subscription bit for SMS notification
          		if(!strSMSNoSubscription.equals(strNewSMSNoSubscription)){
					if (strSMSNoSubscription.equals("0") && strNewSMSNoSubscription.equals("1") && !strNewSMSNo.equals("")){
						EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.SMS_NOTIFY_SUBSCRIPTION, cfiAccount.getExternalKey(), ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strNewSMSNo, "", "", "");
	                    //acctDetails.updateSMSSubscription(connection, strAcctExtKey,strNewSMSNoSubscription);
	                    acctDataBean.setSMSSubscription(strNewSMSNoSubscription);
					}else if (strSMSNoSubscription.equals("1") && strNewSMSNoSubscription.equals("0")){
						EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.SMS_NOTIFY_UNSUBSCRIPTION,cfiAccount.getExternalKey(), ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strNewSMSNo, "", "", "");
	                    //acctDetails.updateSMSSubscription(connection, strAcctExtKey,strNewSMSNoSubscription);
	                    acctDataBean.setSMSSubscription(strNewSMSNoSubscription);
					}
				}

          		// If there is a changes in the subscription bit for account
          		if(!strAccountSubscription.equals(strNewAccountSubscription)){
					if (strAccountSubscription.equals("0") && strNewAccountSubscription.equals("1")){
	                    //acctDetails.updateAcctSubscription(connection, strAcctExtKey,strNewAccountSubscription);
	                    acctDataBean.setAcctSubscription(strNewAccountSubscription);
					}else if (strAccountSubscription.equals("1") && strNewAccountSubscription.equals("0")){
	                    //acctDetails.updateAcctSubscription(connection, strAcctExtKey,strNewAccountSubscription);
	                    acctDataBean.setAcctSubscription(strNewAccountSubscription);
					}
				}

				if(EbppxCusDBUtil.checkIfEbillSubsExist(connection1,cusDatabase,strAcctExtKey,strCategoryDatabase)){//this is used to check if the data exist in the info_cust_text table
						// If there is a changes in the subscription bit for Email bill delivery
						if(!strEmailSubscription.equals(strNewEmailSubscription)){
                    		if (strEmailSubscription.equals("0") && strNewEmailSubscription.equals("1") && !strNewEMailAdd.equals("")){
								EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.EMAIL_DELIVERY_SUBSCRIPTION, cfiAccount.getExternalKey(), ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strNewEMailAdd, "", "", "");
			                    //acctDetails.updateEmailDeliverySubscription(connection, strAcctExtKey,strNewEmailSubscription);
								EbppxCusDBUtil.updateInfoCustText(connection1, cusDatabase,EbppxConstants.EMAIL_DELIVERY_SUBSCRIPTION, kenanAccounNo);
			                    acctDataBean.setEmailSubscription(strNewEmailSubscription);
							}else if (strEmailSubscription.equals("1") && strNewEmailSubscription.equals("0")){
								EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.EMAIL_DELIVERY_UNSUBSCRIPTION,cfiAccount.getExternalKey(), ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strNewEMailAdd, "", "", "");
			                    //acctDetails.updateEmailDeliverySubscription(connection, strAcctExtKey,strNewEmailSubscription);
								EbppxCusDBUtil.updateInfoCustText(connection1, cusDatabase,EbppxConstants.EMAIL_DELIVERY_UNSUBSCRIPTION, kenanAccounNo);
			                    acctDataBean.setEmailSubscription(strNewEmailSubscription);
		                    }
                  		}
					}else{//doesn't exist,insert a new record in info_cust_text
						// If there is a changes in the subscription bit for Email bill delivery
						if(!strEmailSubscription.equals(strNewEmailSubscription)){
                    		if (strEmailSubscription.equals("0") && strNewEmailSubscription.equals("1") && !strNewEMailAdd.equals("")){
								EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.EMAIL_DELIVERY_SUBSCRIPTION, cfiAccount.getExternalKey(), ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strNewEMailAdd, "", "", "");
			                    //acctDetails.updateEmailDeliverySubscription(connection, strAcctExtKey,strNewEmailSubscription);
								EbppxCusDBUtil.insertInfoCustText(connection1, cusDatabase,EbppxConstants.EMAIL_DELIVERY_SUBSCRIPTION, kenanAccounNo);
			                    acctDataBean.setEmailSubscription(strNewEmailSubscription);
							}
						}
					}
					acctDetails.updateAllAcctDetails(connection, strAcctExtKey, strNewAccountSubscription, strNewEmailSubscription, strNewSMSNoSubscription,strNewEMailAdd,strNewSMSNo );
					vecAccountDetails.addElement(acctDataBean);
                }

      connection.commit();//ebps
      connection.setAutoCommit(true);

      connection1.commit();//kenan
      connection1.setAutoCommit(true);
      System.out.println("Transaction has been committed");

            req.setAttribute(EbppxConstants.BILL_SUBSCRIPTIONS, vecBillSubscriptions);
            req.setAttribute(EbppxConstants.CFI_ACCOUNTS, cfiAccounts);
            req.setAttribute(EbppxConstants.SELFCARE_ACKNOWLEDGEMENT, "1");
            req.setAttribute(EbppxConstants.ACCT_DETAILS, vecAccountDetails);
            forwardToMappedUrl(req, res, EbppxConstants.URL_JSP_PARAM);
        }catch (SQLException e) {
            throw new ServletException(e);
        }catch (Throwable t){
            throw new ServletException(t.toString(), t);
        }finally {
      try {
		  connection.rollback();
		  connection1.rollback();
        if (stmt!=null){
          stmt.close();
        }
        if (connection!=null){
          EbppxCusDBUtil.freeDbConnection(connection);
        }
        if (connection1!=null){
          EbppxCusDBUtil.freeKenanDbConnection(connection1);
        }
      }catch (SQLException e1) {
        throw new ServletException(e1);
      }catch (Throwable t1){
        throw new ServletException(t1.toString(), t1);
      }
    }
    }
}